const app = getApp();
Page({
  data: {
    xhx_images: app.xhx_images,
    xhx_route: app.xhx_route,
    msg: "请稍等...",
  },
  onLoad,
  onShow,
  previewImage, //预览图片
  previewVideo, //预览视频
  details,
  clickFollow, //关注
  clickPraise, //点赞
  clickColl, //收藏
  showAll, //展开
  sendCom, //发送评论
  getComs, //获取评论列表
  navToComs, //跳转到评论列表
  onShareAppMessage: function() {
    const that = this;
    const uuid = that.data.uuid;
    return {
      title: '',
      path: app.xhx_route.homeList + "?uuid=" + uuid
    }
  }
})

function onLoad(options) {
  const that = this;
  const uuid = options && options.uuid || 0;
  const tabId = options && options.tabId || 1;
  that.setData({
    uuid,
  })

  wx.getLocation({
    type: 'gcj02',
    success(res) {
      console.log(res)
      that.setData({
        latitude: res.latitude,
        longitude: res.longitude,
      })
      that.details();
    },
    fail: function(res) {
      that.details();
    }
  })

  that.getComs();
}

function onShow() {
  const that = this;
  that.setData({
    myHeadPortrait: app.userInfo.headPortrait || ""
  })
}

function previewImage(event) {
  const that = this;
  const index = event.currentTarget.dataset.index;
  var releaseImg = that.data.releaseImg || [];
  var tempArr = [];
  releaseImg.forEach((item, index) => tempArr.push(item.file));
  wx.previewImage({
    current: tempArr[index],
    urls: tempArr,
  })
}

function previewVideo() {
  const that = this;
  var videoContext = wx.createVideoContext('prew_video');
  videoContext.requestFullScreen();
}

function details() {
  const that = this;
  const uuid = that.data.uuid;
  const latitude = that.data.latitude;
  const longitude = that.data.longitude;

  var reqData = {
    uuid: uuid,
  };

  if (latitude) {
    reqData.latitude = latitude;
    reqData.longitude = longitude;
  }

  app.middleware.requestAjax({
    serAddr: app.serAddrs.contentDetil,
    data: reqData,
    cancelToast: true,
    success: function(res) {
      var temp = res.data;
      let content = temp.releaseContent || "";
      let users = temp.mentionUserList || [];
      let labelList = temp.labelList || [];
      let texts = [];

      temp.msg = "";

      if (users.length > 0) {
        for (let i = 0; i < users.length; i++) {
          let str = `@${users[i].username} `;
          // 当前@的人在最后面。后台保存到数据库时会去除空格
          if (content.indexOf(str) == -1 && (content.substring(content.length - users[i].username.length) == users[i].username)) {
            str = `@${users[i].username}`;
          }
          content = content.replace(new RegExp(str, 'g'), `!@xhx#$${str}^^^^${users[i].userId}!@xhx#$`);
        }
      }

      if (labelList.length > 0) {
        for (let i = 0; i < labelList.length; i++) {
          let str = `#${labelList[i].labelName}#`;
          content = content.replace(new RegExp(str, 'g'), `!@xhx#$${str}vvvv${labelList[i].uuid}!@xhx#$`);
        }
      }

      texts = content.split("!@xhx#$");

      if (texts.length > 0) {

        // 第一期#及@未置入到内容中，默认追加到尾部
        if (texts.length == 1) {

          texts[0] = {
            id: 0,
            text: texts[0],
          }

          if (labelList.length > 0) {
            for (let i = 0; i < labelList.length; i++) {
              texts.push({
                id: texts.length,
                text: `#${labelList[i].labelName}#`,
                labelUuid: labelList[i].uuid,
              })
            }
          }

          if (users.length > 0) {
            for (let i = 0; i < users.length; i++) {
              texts.push({
                id: texts.length,
                text: `@${users[i].username} `,
                userId: users[i].userId,
              })
            }
          }
        } else {
          for (let i = 0; i < texts.length; i++) {
            let text = texts[i];
            let userId = "",
              labelUuid = "";

            if (text) {
              let arr = text.split("^^^^");
              if (arr.length == 2) {
                userId = arr[1];
                text = arr[0];
              } else {
                arr = text.split("vvvv");
                if (arr.length == 2) {
                  labelUuid = arr[1];
                  text = arr[0];
                }
              }
            }

            texts[i] = {
              id: i,
              text,
            };

            if (userId) texts[i].userId = userId;
            if (labelUuid) texts[i].labelUuid = labelUuid;
          }
        }
      }

      temp.texts = texts;

      try {
        temp.releaseImg = JSON.parse(temp.releaseImg);
      } catch (e) {
        temp.releaseImg = [];
      }
      try {
        temp.releaseVideo = JSON.parse(temp.releaseVideo);
      } catch (e) {
        temp.releaseVideo = [];
      }

      that.setData(temp)
    },
    fail: function(res) {
      that.setData({
        msg: res && res.msg || ""
      })
    }
  })
}

function clickFollow(event) {
  const that = this;
  var focusStatus = that.data.focusStatus;
  var releaseAccount = that.data.releaseAccount || 0;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  var reqData = {
    focusAccount: releaseAccount,
  };
  var serAddr = app.serAddrs.addFocus;

  if (focusStatus == 1) {
    serAddr = app.serAddrs.delFocus;
  }

  app.middleware.requestAjax({
    serAddr: serAddr,
    data: reqData,
    success: function(res) {
      that.setData({
        focusStatus: focusStatus == 1 ? 0 : 1,
      })
    },
    complete: function(res) {
      app.middleware.showToast(res && res.msg || "操作失败");
    }
  })
}

function clickPraise(event) {
  const that = this;
  const uuid = that.data.uuid || 0;
  var likesStatus = that.data.likesStatus || 0;
  var likesCount = that.data.likesCount || 0;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  var reqData = {
    trendsId: uuid,
  };
  var serAddr = app.serAddrs.comfirmLike;

  if (likesStatus == 1) {
    serAddr = app.serAddrs.cancelLike;
  }

  app.middleware.requestAjax({
    serAddr: serAddr,
    data: reqData,
    success: function(res) {
      if (likesStatus == 1) {
        likesStatus = 0;
        likesCount--;
      } else {
        likesStatus = 1;
        likesCount++;
      }
      that.setData({
        likesStatus,
        likesCount,
      })

      var prevPage = getCurrentPages()[getCurrentPages().length - 2];

      if (prevPage.route == "pages/home/list/list") {
        var lists = prevPage.data.lists || [];

        lists.forEach((item, index) => {
          if (item.uuid == uuid) {
            lists[index].likesStatus = likesStatus;
            lists[index].likesCount = likesCount;
          }
        })

        prevPage.setData({
          lists,
        })
      }

    },
    complete: function(res) {
      app.middleware.showToast(res && res.msg || "操作失败");
    }
  })
}

function clickColl(event) {
  const that = this;
  const uuid = that.data.uuid || 0;
  var collectionStatus = that.data.collectionStatus || 0;
  var collectionCount = that.data.collectionCount || 0;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  var reqData = {
    trendsId: uuid,
  };
  var serAddr = app.serAddrs.comfirmColl;

  if (collectionStatus == 1) {
    serAddr = app.serAddrs.cancelColl;
  }

  app.middleware.requestAjax({
    serAddr: serAddr,
    data: reqData,
    success: function(res) {
      if (collectionStatus) {
        collectionStatus = 0;
        collectionCount--;
      } else {
        collectionStatus = 1;
        collectionCount++;
      }
      that.setData({
        collectionStatus,
        collectionCount,
      })
    },
    complete: function(res) {
      app.middleware.showToast(res && res.msg || "操作失败");
    }
  })
}

function showAll() {
  const that = this;
  that.setData({
    showAllText: true,
  })
}

function sendCom(event) {
  const that = this;
  const value = event.detail.value.value.trim();
  const uuid = that.data.uuid;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  if (!value) return;

  var reqData = {
    contentUuid: uuid, //动态uuid
    supperCommentUuid: '0', //上一级评论uuid,不存在则为“0”
    supperUserUuid: '0', //上一级评论会发布人uuid
    userUuid: myInfo.userId, //当前评论发布人uuid
    comment: value, //评论内容
    fatherCommentUuid: '0', //最上级评论uuid
    remark: '',
  };

  app.middleware.requestAjax({
    serAddr: app.serAddrs.commentAdd,
    data: reqData,
    success: function(res) {
      const coms = that.data.coms || [];
      coms.unshift({
        username: myInfo.username,
        comment: value
      })
      that.setData({
        coms,
        comValue: "",
        commentCount: (that.data.commentCount || 0) + 1
      })
    },
    complete: function(res) {
      app.middleware.showToast(res && res.msg || "操作失败");
    }
  })
}

function getComs() {
  const that = this;
  const uuid = that.data.uuid;

  var reqData = {
    pageNum: 1,
    pageSize: 5,
    contentUuid: uuid, //动态uuid
  };

  app.middleware.requestAjax({
    serAddr: app.serAddrs.commentList,
    data: reqData,
    cancelToast: true,
    success: function(res) {
      that.setData({
        coms: res.data
      })
    }
  })
}

function navToComs() {
  const that = this;
  const uuid = that.data.uuid;

  wx.navigateTo({
    url: app.xhx_route.homeComs + "?uuid=" + uuid,
  })
}